namespace :import_data do
  require 'csv'

  desc 'import product_a'
  task import_product_a_from_csv: :environment do
    content = File.read(Rails.root.join('products.csv'))
    csv = CSV.parse(content, headers: true)
    csv.each do |row|
      id, name, url, summary, description, published_at, weibo, weixin,
        logo, category, plat, contact_name, contact_company, contact_title, contact_email,
        contact_phone, contanc_weixin, review, statu, created_at, updated_at, photos = row.to_hash.values
      if logo
        begin
          logo_file = MiniMagick::Image.open(logo)
          logo_file.write("#{name.gsub(/\//, "")}_logo.jpg")
        rescue Exception=> e
          print e
        end
      end
      if published_at.split('-').size >= 3
        z_published_at = Date.new(published_at.split('-')[0].to_i, published_at.split('-')[1].to_i, published_at.split('-')[2].to_i)
      end
      if category == '互联网硬件'
        category = 'internet_hardware'
      else
        category = 'internet_software'
      end
      contacts = [{'name'=>"#{contact_name}", 'email'=> "#{contact_email}", 'mobile'=>"#{contact_phone}", 'position'=>"#{contact_title}"}]
      created_at = Time.at(created_at.to_i)
      updated_at = Time.at(updated_at.to_i)
      logo_file = nil
      logo_file = File.open("#{name}_logo.jpg") if File.exist?("#{name}_logo.jpg")
      begin
        a = ProductA.create(logo: logo_file, name: name, summary: summary,
          description: description, published_at: z_published_at, url: url, category: category,
          contacts: contacts, created_at: created_at, updated_at: updated_at)
      rescue Exception => e
        print e
      ensure
        File.delete("#{name}_logo.jpg") if File.exist?("#{name}_logo.jpg")
      end
      unless photos.blank?
        photos.split(',').each_with_index do |photo, index|
          begin
            screen_file = MiniMagick::Image.open(photo)
            screen_file.write("#{name.gsub(/\//, "")}_screen_#{index}.jpg")
            screen_file = nil
            screen_file = File.open("#{name.gsub(/\//, "")}_screen_#{index}.jpg") if File.exist?("#{name.gsub(/\//, "")}_screen_#{index}.jpg")
            if a
              a.screenshots.create(file: screen_file)
            end
          rescue Exception=> e
            print e
          ensure
            File.delete("#{name.gsub(/\//, "")}_screen_#{index}.jpg") if File.exist?("#{name.gsub(/\//, "")}_screen_#{index}.jpg")
          end
        end
      end
      print('success')
    end
  end
end
